package com.pingan.haofang.searchcloud.batch.demo;

import com.pingan.haofang.searchcloud.batch.common.Batch;
import com.pingan.haofang.searchcloud.common.redis.RedisQueue;
import com.pingan.haofang.searchcloud.common.redis.impl.QueueListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * 定时任务刷新
 *
 * @author LUYI374
 * @date 2017年5月8日
 * @since 1.0.0
 */
@Batch(value = "demoRedisListenerCronTask", permanent = true)
@ConditionalOnProperty("demoRedisListenerCronTask")
public class DemoRedisListenerCronTaskRunner {

    static Logger LOG = LoggerFactory.getLogger(DemoRedisListenerCronTaskRunner.class);

    @Resource(name = "redisQueueTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Scheduled(initialDelay = 2000, fixedDelay = 10000)
    public void run() {

        QueueListener listener = new QueueListener();

        System.out.println(System.currentTimeMillis());
        Set<String> keySet = new HashSet<String>();
        keySet.add("test_0");
        keySet.add("test_1");

        for (String key : keySet) {
            RedisQueue queue = new RedisQueue();
            queue.setKey(key);
            queue.setListener(listener);
            queue.setRedisTemplate(redisTemplate);
            try {
                queue.bound();
            } catch (Exception e) {
                System.out.println(e);
            }
            Thread listenerThread = null;
            if (listener != null) {
                listenerThread = queue.new ListenerThread();
            }
            queue.pushFromHead("test:app" + key);
            taskExecutor.execute(listenerThread);
        }
    }
}
